﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using GPainter.Data;
using GPainter.Interfaces;

namespace GPainter.ElementViews
{
    
    public partial class NodeView:INodeView
    {
        //свойство, характеризующее выделение
        private bool _isSelected;
        public bool IsSelected
        {
            get
            {
                return _isSelected;
            }
            set
            {
                _isSelected = value;
                SetBorderVisibiluty(_isSelected ? Visibility.Visible : Visibility.Hidden);
            }
        }

        private void SetBorderVisibiluty(Visibility visibility)
        {
            TopLine.Visibility = visibility;
            BottomLine.Visibility = visibility;
            LeftLine.Visibility = visibility;
            RightLine.Visibility = visibility;
        }


        public string NodeText
        {
            get
            {
                return textNode.Text;
            }
            set
            {
                textNode.Text = value;
            }
        }
      
        private readonly double _borderHeight;//высота бордера
        private readonly double _gridHeight;//высота грида

        private const byte ElementHeight = 18;//высота элемента в тривью
        private const byte Offset = 10;//смещение 

        public NodeView()
        {
            InitializeComponent();
            _borderHeight = PART_Brd.Height;
            _gridHeight = grdMain.Height;

        }

     
        private int GetTreeViewItemCount(TreeViewItem trItem)
        {
            if (!trItem.IsExpanded) return 1;
            int iCount = 1;
            foreach (TreeViewItem trI in trItem.Items)
            {
                if (trI.IsExpanded) iCount += GetTreeViewItemCount(trI);
                else iCount++;
            }
            return iCount;
        }


        //получение количества детей в тривьюшке
        private int GetItemsCount(TreeView tr)
        {
            int itemCount = 0;
            foreach (TreeViewItem trItem in tr.Items)
            {
                itemCount += GetTreeViewItemCount(trItem);
                // MessageBox.Show(trItem.ActualHeight.ToString());
            }
            return itemCount;
        }



        //привести к развернутому виду
        private void ChangeSizeToExpanded()
        {
            double newHeight = ElementHeight * GetItemsCount(PART_TrHierarhy);
            PART_TrHierarhy.Height = newHeight;
            contentPr.Height = new GridLength(Offset + newHeight);
            PART_Brd.Height = _borderHeight + newHeight + Offset * 2;
            grdMain.Height = _gridHeight + newHeight;
            Height = _borderHeight + Offset * 2 + newHeight;
          //  OnRestoreNodePosition(this, new RoutedEventArgs());
        }



        private void PART_TrHierarhy_Expanded(object sender, RoutedEventArgs e)
        {
            ChangeSizeToExpanded();
        }

        public void BtnExp_Checked(object sender, RoutedEventArgs e)
        {
            if ((bool)BtnExp.IsChecked)
            {
                ChangeSizeToExpanded();
            }
            else
            {
                contentPr.Height = new GridLength(0);
                PART_Brd.Height = _borderHeight;
                grdMain.Height = _gridHeight;
                Height = _borderHeight;
                //OnRestoreNodePosition(this, new RoutedEventArgs());
            }

        }

        /// <summary>
        /// рекурсивное заполнение тривью, начиная со второго уровня
        /// </summary>
        /// <param name="treeViewItem"></param>
        /// <param name="childs"></param>
        private void FillTreeView(TreeViewItem treeViewItem, IEnumerable<MyTreeViewItem> childs)
        {
            if (childs == null) return;
            foreach (var myTr in childs)
            {
                var trItem = new TreeViewItem {Header = myTr.Header};
                treeViewItem.Items.Add(trItem);
                FillTreeView(trItem, myTr.Childs);
            }
        }

        /// <summary>
        /// заполнение тривью
        /// </summary>
        /// <param name="visualTree"></param>
        public void InitTreeView(MyTreeViewItem visualTree)
        {
            foreach (var item in visualTree.Childs)
            {
                var tr = new TreeViewItem { Header = item.Header };
                PART_TrHierarhy.Items.Add(tr);//добавляем в тривью
                FillTreeView(tr, item.Childs);
            }
        }

        //TODO не должно быть такого рода событий!!!!
        /// <summary>
        ///cобытие, возникающее при икспанде 
        /// </summary>
        public event EventHandler<RoutedEventArgs> OnRestoreNodePosition;

        //данные описывающие вершину
        public INodeData DataNode { get; set; }

        private double _oldPosition;
      
        private void RightLine_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _oldPosition = e.GetPosition(Parent as IInputElement).X;
        }

        private void RightLine_MouseMove(object sender, MouseEventArgs e)
        {
            if(e.LeftButton == MouseButtonState.Pressed)
            {
               var currentPosition = e.GetPosition(Parent as IInputElement);
               Width += currentPosition.X - _oldPosition;
               _oldPosition = currentPosition.X;
               TopLine.X2 = Width;
               BottomLine.X2 = Width;
            }
        }
    }
}
